package com.landiao.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.landiao.common.utils.CodecUtils;
import com.landiao.entities.Coupon;
import com.landiao.entities.CouponShopRela;
import com.landiao.mapper.CouponMapper;

@Service
public class CouponService extends BaseService<Coupon, String>{
	@Autowired
	private CouponShopRelaService couponShopRelaService;
	
	@Override
	protected CouponMapper getBaseMapper() {
		// TODO Auto-generated method stub
		return (CouponMapper)baseMapper;
	}


	public void updateStateById(String id) {
		// TODO Auto-generated method stub
		getBaseMapper().updateStateById(id);
	}

	@Override
	public void save(Coupon t) {
		String[] list = t.getShopList();
		t.setState("10X");
		t.setSurplusNum(t.getTotalNum());
		CouponShopRela rela = new CouponShopRela();//用于保存关联门店
		rela.setCompId(t.getCompId());
		String couponId = CodecUtils.getUUID();
		t.setCouponId(couponId);
		//设置卡券编号
		t.setNo("KQ"+CodecUtils.getDateNum());
		getBaseMapper().insert(t);
		if(t.getShopRange().equals("ZDMD")){
			//保存关联的门店
			if(list!=null&&list.length>0){
				for(int j=0;j<list.length;j++){
					rela.setCouponShopRelaId(CodecUtils.getUUID());
					rela.setCouponId(couponId);
					rela.setShopId(list[j]);
					couponShopRelaService.save(rela);
				}
			}
		}
	}


	@Override
	public void update(Coupon t) {
		// TODO Auto-generated method stub
		t.setSurplusNum(t.getTotalNum());
		getBaseMapper().updateByPrimaryKeySelective(t);
		//删除原来关联的门店(更新的时候不管范围先把原来的关联门店删除)
		couponShopRelaService.deleteByCouponId(t.getCouponId());
		if(t.getShopRange().equals("ZDMD")){
			//新增现在的关联门店
			String[] list = t.getShopList();
			CouponShopRela rela = new CouponShopRela();//用于保存关联门店
			rela.setCompId(t.getCompId());
			if(list!=null&&list.length>0){
				for(int j=0;j<list.length;j++){
					rela.setCouponShopRelaId(CodecUtils.getUUID());
					rela.setCouponId(t.getCouponId());
					rela.setShopId(list[j]);
					couponShopRelaService.save(rela);
				}
			}
		}
		
	}
	
}
